package com.example.demo.http.middlewares;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.demo.services.system.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

//装载用户信息的拦截器
public class AuthenticateLoadMiddleware implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String auth = request.getHeader("Authorization");

        //如果Auth头不是null，则判断有没有JWT
        if (auth != null) {
            //删掉Bearer标记头
            auth = auth.replace("Bearer ", "");
            //送到token进行解析
            try {
                //如果token正确，则此时就会装上用户
                UserService.getThreadInstance().parseToken(auth);
                //标记用户是否装载
            } catch (JWTVerificationException e) {
                //如果报错了，则把错误信息装载到临时位置，根据后续是否要扔掉信息或者使用信息
                Objects.requireNonNull(RequestContextHolder.getRequestAttributes()).setAttribute("msg", e.getMessage(), RequestAttributes.SCOPE_REQUEST);
                //e.printStackTrace();
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
